package m.jclecai.com.view.common;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.bean.common.MissDataTrendBean;

/**
 * Created by mwh on 2017/10/28.
 * 欲出率的自定义View;
 *
 * 最新版本的TrendView视图
 * 这个和之前的相比，主要在于这里的格子并不再是固定的宽高，
 * 而是根据屏幕来计算得到的；
 * 这里的这个类，我们和之前的相比存在不同的是，
 * 这里我们的高度是固定的，我们将遗漏的最大值作为纵坐标的最大值；
 * 这里我们将水平方向上面定为13个格子[0,12]
 * 数直方向上面的定义11个格子；[0,10]
 */

public class TrendView extends View {

    private Paint mXPointPaint;

    public float XWidth=0;
    public float YHeight=0;

    public List<String> mStringList=new ArrayList<>();
    private Paint mLinePaint;
    private Paint mNumberPaint;

    public int trendLineColor=0xFFed912d;
    public int maxLineColor=0xFFea624d;
    public int aveLineColor=0xFF09ae8f;

    public int titleTextColor=0xFFb7b7b8;

    int [] mMissData={42,66,0,17,112};

    List<TrendBean> mTrendBeen=new ArrayList<>();

    //历史最大的遗漏值；
    public float mHistoryMaxMissData;

    //平均的遗漏值
    public float mAvgMissData;

    //10次最大的遗漏值；
    public float mMaxMissData;

    //当前遗漏值遗漏值；
    public float mCurMissData;

    //水平方向上和垂直方向上的格子的个数
    private float mXNumber=13;
    private float mYNumber=9;

    private Paint mTrendPaint;
    private Paint mDottedLinePaint;

    public float mMissDataLineLenght = 0;


    //走势图线的高度；
    public int mLineHeight;
    //遗漏等数字显示的大小
    public int mTextSize;
    //折线点上的小圆点的半径
    public int mBallRadius;

    public TrendView(Context context) {
        this(context,null);
    }

    public TrendView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public TrendView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mLineHeight = context.getResources().getDimensionPixelSize(R.dimen.trend_view_line_height);
        mTextSize = context.getResources().getDimensionPixelSize(R.dimen.trend_view_text_size);
        mBallRadius = context.getResources().getDimensionPixelSize(R.dimen.trend_view_ball_radius);
        init();
    }

    private void init() {

        for (int i = 0; i < 10; i++) {
            mStringList.add(i+"");
        }

        //小圆点的画笔；
        mXPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mXPointPaint.setColor(trendLineColor);

        //数字的画笔；
        mNumberPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mNumberPaint.setColor(trendLineColor);
        mNumberPaint.setTextSize(mTextSize);


        //直线的画笔；
        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mLinePaint.setColor(Color.GREEN);

        mLinePaint.setStrokeWidth(mLineHeight);

        //折线的画笔；
        mTrendPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTrendPaint.setStyle(Paint.Style.STROKE);
        mTrendPaint.setColor(trendLineColor);

        mTrendPaint.setStrokeWidth(mLineHeight);

        //虚线的画笔；
        mDottedLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);
        mDottedLinePaint.setColor ( trendLineColor ) ;
        //设置画直线格式
        mDottedLinePaint.setStyle ( Paint.Style.STROKE ) ;

        mDottedLinePaint.setStrokeWidth(mLineHeight);
        //设置虚线效果
        mDottedLinePaint.setPathEffect ( new DashPathEffect( new float [ ] { 8,5  }, 0 ) ) ;

    }




    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        //====创建坐标系===
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();

        XWidth = measuredWidth/mXNumber;
        YHeight = measuredHeight/mYNumber;

        mMissDataLineLenght =XWidth*10;

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        mTrendBeen.clear();


        for (int i : mMissData) {
            mMaxMissData = mMaxMissData<i?i:mMaxMissData;
        }
        //我们是需要在这里进行一个初始化的，否者是会出事情的；
        for (int i = 0; i < mMissData.length; i++) {
            float j=getYByMissData(mMissData[i]);
            RectF rectF = toRealPoint(i+0.5f, j);
            TrendBean trendBean = new TrendBean(rectF, mMissData[i]);
            mTrendBeen.add(trendBean);
        }

        System.out.println("mTrendBeen: "+mTrendBeen);


        for(int i = 0; i< mXNumber; i++){
            //垂直方向
           // canvas.drawLine(i*XWidth,0,i*XWidth,getMeasuredHeight(),mLinePaint);
        }

        for (int i = 0; i< mYNumber; i++){
            //水平方向
            if(i==mYNumber-1){
                mLinePaint.setColor(0xFF404246);
                canvas.drawLine(0,i*YHeight,getMeasuredWidth(),i*YHeight,mLinePaint);
            }//404246

        }
        //==填充水平坐标值；===
        mNumberPaint.setColor(trendLineColor);
        for(int i = 0; i< mMissData.length-1; i++){

            float left=(i)*XWidth;
            float top=(mYNumber -1)*YHeight;
            float right=left+XWidth;
            float bottom=top+YHeight;
            RectF rect = new RectF(left,top,right,bottom);

            Rect nubmerRect = new Rect();
            String number = mMissData[i] + "";
            mNumberPaint.getTextBounds(number,0,number.length(),nubmerRect);
            //将坐标进行一个填充
            canvas.drawText(number,rect.left+((XWidth-nubmerRect.width())/2),rect.top+((YHeight+nubmerRect.height())/2),mNumberPaint);
        }

        //这里我们需要将纵坐标也进行一个填充
        for(int i = 0; i< mYNumber; i++){
            RectF rect=toRealPoint(0,i);
            Rect nubmerRect = new Rect();
            String number = i + "";
            mNumberPaint.getTextBounds(number,0,number.length(),nubmerRect);
            //将坐标进行一个填充
           // canvas.drawText(i+"",rect.left+((XWidth-nubmerRect.width())/2),rect.top+((YHeight+nubmerRect.height())/2),mNumberPaint);
        }


        Path path = new Path();
        //画折线；
        path.moveTo(mTrendBeen.get(0).getPointF().x,mTrendBeen.get(0).getPointF().y);

        for (TrendBean trendBean : mTrendBeen) {
            path.lineTo(trendBean.getPointF().x,trendBean.getPointF().y);
        }
        canvas.drawPath(path,mTrendPaint);


        //这里是画最后一个点的虚线的圆形；

        //PointF lastCirclePoint = mAllPoints.get(mAllPoints.size() - 1);
        TrendBean lastTrendBean = mTrendBeen.get(mTrendBeen.size() - 1);
        PointF lastCirclePoint = lastTrendBean.getPointF();

        canvas.drawCircle(lastCirclePoint.x,lastCirclePoint.y,(int)(1.5f*mBallRadius), mDottedLinePaint);

        Path dottedPath = new Path();




        //这里我们从最后一个点向下垂直方向画一条虚线；
        RectF rectF = toRealPoint(lastCirclePoint.x, 0);
        dottedPath.moveTo(lastCirclePoint.x,lastCirclePoint.y);
        dottedPath.lineTo(lastCirclePoint.x,rectF.top+YHeight/2);
        dottedPath.lineTo(lastCirclePoint.x+2*mBallRadius,rectF.top+YHeight/2);
        canvas.drawPath(dottedPath,mDottedLinePaint);

        Rect rect = new Rect();
        //mNumberPaint.getTextBounds("当前遗漏",0,"当前遗漏".length(),rect);
        mNumberPaint.getTextBounds(mCurMissData+"",0,(mCurMissData+"").length(),rect);

        canvas.drawText("当前遗漏"+lastTrendBean.getMissData(),lastCirclePoint.x+2*mBallRadius,rectF.top+YHeight/2+rect.height()/2,mNumberPaint);
        //这里我们是需要画path才能画出虚线；
        //canvas.drawLine(lastCirclePoint.x,lastCirclePoint.y,lastCirclePoint.x,rectF.top,mDottedLinePaint);
        //这里接着画历史和十次最大；
        //这里的话，我们接着画遗漏线；

        //历史最高的遗漏的线：
        TrendBean mostTrendBean=null;
        for (TrendBean trendBean : mTrendBeen) {
            if (mostTrendBean == null) {
                mostTrendBean=trendBean;
            }
            if(trendBean.getMissData()>mostTrendBean.getMissData()){
                mostTrendBean=trendBean;
            }
        }
        //然后划线；
        mLinePaint.setColor(Color.MAGENTA);
        mLinePaint.setColor(maxLineColor);
        canvas.drawLine(0,mostTrendBean.getPointF().y,mMissDataLineLenght,mostTrendBean.getPointF().y,mLinePaint);

        Rect textRect = new Rect();
        mNumberPaint.setColor(maxLineColor);
        mNumberPaint.getTextBounds("十次最大",0,"历史平均".length(),textRect);
        canvas.drawText("十次最大:"+mostTrendBean.getMissData(),mMissDataLineLenght+10,mostTrendBean.getPointF().y+textRect.height()/2,mNumberPaint);


        //这里我们是需要画平均遗漏的横线；

        float yByMissData = getYByMissData(mAvgMissData);
        mLinePaint.setColor(aveLineColor);
        canvas.drawLine(0,toRealPoint(0,yByMissData).top, mMissDataLineLenght,toRealPoint(0,yByMissData).top,mLinePaint);
        //这里在线的尽头，我们画上数据；

       // Rect textRect = new Rect();
        mNumberPaint.setColor(aveLineColor);
        mNumberPaint.getTextBounds("历史平均",0,"历史平均".length(),textRect);
        canvas.drawText("历史平均:"+mAvgMissData,mMissDataLineLenght+10,toRealPoint(0,yByMissData).top+textRect.height()/2,mNumberPaint);


        //画中间的部分；
        mNumberPaint.setColor(titleTextColor);
        String title = "近10次遗漏走势图";
        mNumberPaint.getTextBounds(title,0,title.length(),textRect);
        canvas.drawText(title,(getMeasuredWidth()-textRect.width())/2,YHeight+(textRect.height())/2,mNumberPaint);
        //画文字
        String maxHistory= "历史最大 "+mHistoryMaxMissData ;
        mNumberPaint.getTextBounds(maxHistory,0,maxHistory.length(),textRect);
        canvas.drawText(maxHistory,(getMeasuredWidth()-textRect.width()-XWidth),YHeight+(textRect.height())/2,mNumberPaint);

        //最后画小圆点
        for (TrendBean trendBean : mTrendBeen) {
            canvas.drawCircle(trendBean.getPointF().x,trendBean.getPointF().y,mBallRadius,mXPointPaint);
        }
    }

    /**
     * 通过传入一个遗漏值，来得到其Y坐标；
     * 这里是将一个值除100，得到其百分比，
     * 然后乘以我们坐标系的值，由于我们坐标系，高度只有10个格子
     * 所以我们再乘以10，再除以2，以此来表示更大的坐标的值；也就是说我们坐标系，最多表示0到200的遗漏值；
     * @param data
     * @return
     */
    public float getYByMissData(float data){
        float v = (mMaxMissData / (mYNumber-3));
        return data/v;
    }


    /**
     * 传入显示的 坐标，返回实际点在屏幕显示的坐标；
     */
    public RectF toRealPoint(float x, float y){

        //这里我们是需要将（0，0）--->(0,YNumber-1)
        //这里我们是需要将（0，5）--->(0,0)
        //这里我们将（17，5）     --->(XNumber-1,0)
        //这里我们发现一个问题就是，横坐标没有变化，纵坐标变成YNumber-1-y

        //left，top,bootom，with，height
        //进行一个坐标的转换；
        float realX=x;
        float realY=mYNumber-1-y;

        float left=realX*XWidth;
        float top=realY*YHeight;
        float right=left+XWidth;
        float bottom=top+YHeight;
        RectF rect = new RectF(left,top,right,bottom);

        return rect;
    }



    public void setMissDataTrendBean(MissDataTrendBean.MisscodesTreanBean missDataTrendBean){

        //String[] codes = missDataTrendBean.getCodes().split(",");
        Object[] codes=  missDataTrendBean.getList().toArray();
        //这里的max历史的最大值，并不是10次的最大值；
        String max=missDataTrendBean.getMax();
        String avg=missDataTrendBean.getAve();
        String cur=missDataTrendBean.getCur();
        String out = missDataTrendBean.getOut();

        mMissData=new int[codes.length];
        for (int i = 0; i < codes.length; i++) {
            mMissData[i]=Integer.parseInt(codes[i].toString());
        }

        mHistoryMaxMissData=Float.parseFloat(max);
        mAvgMissData=Float.parseFloat(avg);
        mCurMissData=Float.parseFloat(cur);

        requestLayout();
    }

    /**
     * 走势图的bean对象封装的有一个Point和一个遗漏值；
     */
    public class TrendBean{
        PointF mPointF;
        float missData;
        RectF mRectF;

        public TrendBean(RectF pointF, float missData) {
            this.mRectF=pointF;
            mPointF =new PointF(pointF.left,pointF.top);
            this.missData = missData;
        }

        public PointF getPointF() {
            return mPointF;
        }

        public void setPointF(PointF pointF) {
            mPointF = pointF;
        }

        public float getMissData() {
            return missData;
        }

        public void setMissData(float missData) {
            this.missData = missData;
        }

        @Override
        public String toString() {
            return "TrendBean{" +
                    "mPointF=" + mPointF +
                    ", missData=" + missData +
                    ", mRectF=" + mRectF +
                    '}';
        }
    }
}
